<?php

class detailAction extends FirstendAction
{

    public function _initialize()
    {
        parent::_initialize();
        $this->_mod = D('items')->cache(true, 3600);
        $this->_mod_see = D('items_see');
        $this->baidu_url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=IcuTnk84EyWKA4groWQVPoelvuLXPLsD&output=json&coordtype=wgs84ll&location=";//维度经度
    }


    public function index()
    {
        //是否需要再次获取用户的位置
        $IP = $this->getIP();
        $address_cache = S('items-'.$IP.'-true');
        if ($address_cache){
            $this->assign('is_address', 'false');
        }else{
            $this->assign('is_address', 'true');
        }
        $id = I('id', '', 'trim');
        //通过微信点击进来的
        if (isset($_GET['channel']) && $_GET['channel'] == 'wx'){
            $this->assign('channel', 'wx');
        }else{
            $this->assign('channel', 'detail');
        }
        $item = $this->_mod->where(array('id' => $id))->find();
        !$item && $this->_404();
        $this->insertItemsHits($id, $item['hits']);
// 高佣金接口 开始 

        if ($this->getRobot() == false) {
            $last_time = date('Y-m-d', $item['last_time']);
            $today = date('Y-m-d', time());

//if($last_time!=$today || $item['ding']==1 || ($item['tk']==1 && $item['que']==0) ){
            if ($last_time != $today) {
//if('1'=='1'){	
                $api_err = 'no';
                $apiurl = $this->tqkapi . '/gconvert';
                $apidata = array(
                    'tqk_uid' => $this->tqkuid,
                    'time' => time(),
                    'good_id' => '' . $item['num_iid'] . ''
                );
                $token = $this->create_token(trim(C('yh_gongju')), $apidata);
                $apidata['token'] = $token;
                $res = $this->_curl($apiurl, $apidata, false);
                $res = json_decode($res, true);
                $me = $res['me'];
                if (strlen($me) > 0) {
                    $quanurl = 'https://uland.taobao.com/coupon/edetail?e=' . $me . '&activityId=' . $item['Quan_id'] . '&itemId=' . $item['num_iid'] . '&pid=' . trim(C("yh_taobao_pid")) . '&af=1';
                    $kouling = kouling($item['pic_url'] . '_400x400', $item['title'], $quanurl);
                    $data = array(
                        'last_time' => time(),
                        'quankouling' => $kouling,
                        'quanurl' => $quanurl,
                        'ding' => 0,
                        'que' => 1
                    );
                    $re = $this->_mod->where(array(
                        'num_iid' => $item['num_iid']
                    ))->save($data);


                    if ($re) {

                        $item['quankouling'] = $kouling;
                        $item['quanurl'] = $quanurl;
                        $item['que'] = 1;
                    } else {

                        $api_err = 'yes';

                    }

                } else {

                    $api_err = 'yes';

                }

            }
        }

//高佣金接口  结束

        if (C('yh_item_hit')) {
            $hits_data = array('hits' => array('exp', 'hits+1'));
            $this->_mod->where(array('id' => $id))->setField($hits_data);
        }

        $this->_config_seo(C('yh_seo_config.item'), array(
            'title' => $item['title'],
            'intro' => $item['intro'],
            'price' => $item['price'],
            'quan' => floattostr($item['quan']),
            'coupon_price' => $item['coupon_price'],
            'tags' => $tags,
            'seo_title' => $item['seo_title'],
            'seo_keywords' => $item['seo_keys'],
            'seo_description' => $item['seo_desc'],
        ));

        $cid = $item["cate_id"];
        $where = array(
            'cate_id' => $cid,
            'id' => array('neq', $id)
        );
        $orlike = $this->_mod->where($where)->field('id,title,pic_url,coupon_price,price,shop_type')->limit('0,9')->order('is_commend desc,id desc')->select();
        $this->assign('orlike', $orlike);
        if (empty($item['quankouling']) || $item['quankouling'] == '0' || $item['quankouling'] == 'undefined') {
            $kouling = kouling($item['pic_url'] . '_200x200.jpg', $item['title'], $item['quanurl']);
            $item['quankouling'] = $kouling;
            $this->_mod->where(array(
                'num_iid' => $item['num_iid']
            ))->setField('quankouling', $kouling);
        }

        $Now = time();
        $this->assign('uptime', $Now - $item['up_time']);
        $this->assign('item', $item);

        if ($this->getRobot() == false && $api_err == 'yes') {
            $last_time = date('Y-m-d', $item['last_time']);
            $today = date('Y-m-d', time());
//if($last_time!=$today || $item['ding']==1 || ($item['tk']==1 && $item['que']==0) ){
            if ($last_time != $today) {
                if (function_exists('opcache_invalidate')) {
                    $basedir = $_SERVER['DOCUMENT_ROOT'];
                    $dir = $basedir . '/data/runtime/Data/coupon/disable_num_iids.php';
                    $ret = opcache_invalidate($dir, TRUE);
                }
                $disable_num_iids = F('coupon/disable_num_iids');
                if (!$disable_num_iids) {
                    $disable_num_iids = array();
                }
                $is = strpos(serialize($disable_num_iids), $item['num_iid']);
                if (empty($is)) {
                    $disable_num_iids[] = array(
                        'num_iid' => $item['num_iid'],
                        'rate' => $item['commission_rate'],
                        'zc_id' => $item['zc_id']
                    );

                    if (function_exists('opcache_invalidate')) {
                        $basedir = $_SERVER['DOCUMENT_ROOT'];
                        $dir = $basedir . '/data/runtime/Data/coupon/disable_num_iids.php';
                        $ret = opcache_invalidate($dir, TRUE);
                    }

                    F('coupon/disable_num_iids', $disable_num_iids);
                    $data = array(
                        'last_time' => time(),
                        'ding' => 0,
                        'que' => 1,
                    );
                    $this->_mod->where(array(
                        'num_iid' => $item['num_iid']
                    ))->save($data);

                }
            }
        }

        $this->display();

    }

    public function productinfo()
    {
        $num_iid = I('numiid');
        if ($num_iid) {
            $url = 'http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdesc/6.0/?data={"id":"' . $num_iid . '"}';
            $descs = $this->_curl($url);
            $content = json_decode($descs, true);
            $pattern = '/<img((?!src).)*src[\s]*=[\s]*[\'"](?<src>[^\'"]*)[\'"]/i';
            preg_match_all($pattern, $content['data']['pcDescContent'], $out);
            $imglist = $out['src'];
            foreach ($imglist as $k => $v) {
                $images = $i + 1;
                $desc[$k] = '<img class="lazy" src=' . $v . '>';

            }
            $data['desc'] = $desc;
            $json = array(
                'status' => 'ok',
                'content' => $desc
            );
            exit(json_encode($json));
        }


    }


    //增加商品点击量 用IP区分
    public function insertItemsHits($id, $hits)
    {
        $IP = $_SERVER['HTTP_HOST'];
        $ips = S('items_hits_'.$id);
        if (in_array($IP, json_decode($ips, true))){
            return true;
        }else{
            $this->_mod->where('id = '.$id)->save(['hits'=>$hits+1]);
            $data_ip = array_merge($ips, $IP);
            S('items_hits_'.$id, json_encode($data_ip), 0);
        }
    }
    //获取微信config的sign
    public function getSignature()
    {
        $this->url = $_POST['url'];
        $this->getWxTicket();
        $strs = 'jsapi_ticket=' . $this->ticket . '&noncestr=' . self::$noncestr . '&timestamp=' . self::$timestamp . '&url='.$this->url;
        $this->ticketStr = $strs;
        $signature = sha1($strs);
        $json = array(
            'status' => 'ok',
            'signature' => $signature,
            'noncestr' => self::$noncestr,
            'timestamp' => self::$timestamp,
            'appId' => $this->APPID
        );
        Log::write('生成的signature的参数---' . $strs.'生成的signature---' . $signature, Log::INFO, '', 'signature');
        exit(json_encode($json));
    }

    //保存用户访问详情页时的地理位置
    public function saveUserLocation()
    {
        $IP = $_SERVER['REMOTE_ADDR'];
        $address_cache = S('items-'.$IP.'-'.I('post.is_allow'));
        if (!$address_cache || $address_cache == null){
            if(I('post.is_allow')){
                $save_data = [];
                $save_data['latitude'] = I('post.latitude'); // 纬度，浮点数，范围为90 ~ -90
                $save_data['longitude'] = I('post.longitude'); // 经度，浮点数，范围为180 ~ -180。
                $speed = I('post.speed'); // 速度，以米/每秒计
                $accuracy = I('post.accuracy'); // 位置精度
                $_url = $this->baidu_url.$save_data['latitude'].','.$save_data['longitude'];
                $save_data['baidu_text'] = $this->_curl($_url);
                $save_data['add_time'] = date('Y-m-d H:i:s',time());
                $save_data['IP'] = $IP;
                $save_data['is_allow'] = I('post.is_allow');
                $this->_mod_see->save($save_data);
                S('items-'.$IP.'-'.I('post.is_allow'), json_encode($save_data), 24*3600);
            }else{
                $save_data = [];
                $save_data['add_time'] = date('Y-m-d H:i:s',time());
                $save_data['IP'] = $IP;
                $save_data['is_allow'] = I('post.is_allow');
                $save_data['baidu_text'] = isset($_POST['baidu_text']) ? I('post.baidu_text') : "";
                $this->_mod_see->save($save_data);
                S('items-'.$IP.'-'.I('post.is_allow'), json_encode($save_data), 24*3600);
            }
        }
        exit(json_encode(['status'=>'ok']));
    }



}


function floattostr($val)
{
    preg_match("#^([\+\-]|)([0-9]*)(\.([0-9]*?)|)(0*)$#", trim($val), $o);
    return $o[1] . sprintf('%d', $o[2]) . ($o[3] != '.' ? $o[3] : '');
}	